package com.tulei.system.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.tulei.common.constant.RedisConstant;
import com.tulei.common.constant.SystemConstant;
import com.tulei.common.response.R;
import com.tulei.common.utils.RedisUtils;
import com.tulei.common.utils.code.IPUtils;
import com.tulei.common.utils.StringUtils;
import com.tulei.system.Entity.Dto.LoginDto;
import com.tulei.system.Entity.Dto.Modle;
import com.tulei.system.Entity.Dto.TableDto;
import com.tulei.system.Entity.SysUser;
import com.tulei.system.mapper.UserMapper;
import com.tulei.system.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author 29605
* @description 针对表【sys_user】的数据库操作Service实现
* @createDate 2024-06-06 16:53:07
*/
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, SysUser> implements UserService {



    private final RedisUtils redisUtils;


    private final HttpServletRequest request;

    @Override
    public R<Object> login(LoginDto login) {
        String username = login.getUsername();
        if (StringUtils.isEmpty(username))
            return R.warn("用户名不能为空");
        String pwd = login.getPassword();
        if (StringUtils.isEmpty(pwd))
            return R.warn("密码不能为空");
//        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        HttpServletRequest request = attributes.getRequest();
        String ip = IPUtils.getIp(request);
//        if (redisUtils.noHasKey(RedisConstant.code + ":" + ip))
//            return R.warn("验证码已经过期");
        SysUser user = getOne(new QueryWrapper<SysUser>().eq("username", username));
        if (StringUtils.isEmpty(user)) {
            return R.fail("账号不存在");
        }
        int errorNum = 0;
        String key = SystemConstant.userStatus + ":" + username;
        if (redisUtils.hasKey(key)) {
            errorNum = (int) redisUtils.get(key);
        }
        if (errorNum >= SystemConstant.passwordErrorNum)
            return R.fail("此账号因密码错误次数太对，已经被暂时禁用。");
        // 验证密码是否正确
        String sha256 = DigestUtils.md5DigestAsHex((pwd + user.getSalt()).getBytes());//（用户输入的密码+盐值）加密
        String password = user.getPassword();//真正的密码（加密的）
        if (!sha256.equals(password)) {
            long time = SystemConstant.passwordErrorNum_Time;
            redisUtils.set(key, errorNum + 1, time);
            return R.fail("密码错误");
        }

        if (errorNum > 0) redisUtils.del(key);
        StpUtil.login(user.getUserId());
        String token = StpUtil.getTokenValue();
        StpUtil.getSession().set("user", user);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        return R.ok("登录成功", map);
    }

    @Override
    public byte[] getUserImage(String account) {
        return new byte[0];
    }

    @Override
    public boolean updateUserAvatar(Long userId, String avatar) {
        return baseMapper.updateUserAvatar(userId, avatar) > 0;
    }


    @Override
    public boolean checkPhoneUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = baseMapper.checkPhoneUnique(user.getPhone());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return false;
        }
        return true;
    }

    @Override
    public boolean checkEmailUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = baseMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return false;
        }
        return true;
    }


    @Override
    public int updateUserProfile(SysUser user)
    {
        return baseMapper.updateUser(user);
    }
    @Override
    public Map<String, Object> getInfo() {
        String account = (String) StpUtil.getLoginId();

        Map<String, Object> map = new HashMap<>();
        byte[] image = getUserImage(account);
        map.put("image", image);
        return map;
    }

    @Override
    public List<SysUser> selectList(TableDto tableDto, int offset, int pageSize) {
        return baseMapper.selectList(tableDto, offset, pageSize);
    }

    @Override
    public List<Modle> getList() {
        return baseMapper.getList();
    }

}




